package org.example.controller.supplier;

import org.example.entity.Supplier;
import org.example.service.SupplierService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/supplier")
public class supplierController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取所有的供应商列表，就是查询数据库里所有的供应商数据传递给前端页面
//        默认显示第一页
        int pageIndex=0;
        //从jsp页面获取当前页的index
        if(req.getParameter("pageIndex")!=null){
            pageIndex = Integer.parseInt(req.getParameter("pageIndex"));
        }
        //假定固定每页显示5条
        int pageNumber=5;

        //调用实现类和方法，首先查看共有多少记录和多少页
        SupplierService supplierService = new SupplierService();
        try {
            int totalNumber = supplierService.queryAllSuppliersCount(pageNumber);
            int totalPage = (int)Math.ceil(totalNumber/pageNumber);

            List<Supplier> supplierList = new ArrayList<>();
            supplierList = supplierService.queryAllSuppliers(pageIndex,pageNumber);
            req.setAttribute("data",supplierList);
            req.setAttribute("totalpage",totalPage);

            req.setAttribute("preIndex",pageIndex-1);
            if(pageIndex<=0){
                req.setAttribute("preIndex",0);
            }
            req.setAttribute("nextIndex",pageIndex+1);
            if(pageIndex>=totalPage){
                req.setAttribute("nextIndex",totalPage);
            }
            req.getRequestDispatcher("/suppliers/supplier.jsp").forward(req,resp);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
